package convert

import (
	"bytes"
	"reflect"

	"github.com/tealeg/xlsx"
)

// input an go struct array and header name array that will retrun xlsx []byte
func ConvertToXlsx(structArray []interface{}, headerArray []string) ([]byte, error) {
	var xlsxBuf bytes.Buffer
	xlsxFile := xlsx.NewFile()
	sheet, err := xlsxFile.AddSheet("Sheet1")
	if err != nil {
		return nil, err
	}

	// 写入表头
	headerRow := sheet.AddRow()
	for _, head := range headerArray {
		headerRow.AddCell().SetValue(head)
	}

	// 写入数据
	for _, item := range structArray {
		row := sheet.AddRow()
		// 反射获取结构体属性
		t := reflect.TypeOf(item)
		v := reflect.ValueOf(item)
		for i := 0; i < t.NumField(); i++ {
			field := t.Field(i)
			value := v.FieldByName(field.Name)
			row.AddCell().SetValue(value)
		}
	}

	err = xlsxFile.Write(&xlsxBuf)
	if err != nil {
		return nil, err
	}

	return xlsxBuf.Bytes(), nil
}
